//
//  LXLPopView.swift
//  Weibo-YQY-test
//
//  Created by Lang on 10/14/15.
//  Copyright © 2015 Lang. All rights reserved.
//

import UIKit

protocol LXLPopViewDelegate: NSObjectProtocol {
    func popViewWillDismiss()
}

class LXLPopView: UIButton {
    
    weak var delegate: LXLPopViewDelegate?
    
    var imageBack: UIImageView?

    init(customView: UIView){
        super.init(frame: CGRectMake(0, 0, SCREENW, SCREENH))
        addTarget(self, action: "converButtonClick:", forControlEvents: .TouchUpInside)
        //初始化控件
        setupView(customView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupView(customView: UIView) {
        //添加一个箭头的背景图
        let image = UIImage(named: "popover_background")
        let imageBack = UIImageView(image: image?.stretchableImageWithLeftCapWidth(Int(image!.size.width * 0.5), topCapHeight: Int(image!.size.height * 0.5)))
        imageBack.size = CGSizeMake(customView.width+10, customView.height+20)
        self.addSubview(imageBack)
        self.imageBack = imageBack
        
        // 添加 customView,设置x，y 来确定边框的宽度大小
        customView.x = (imageBack.width - customView.width) * 0.5
        customView.y = (imageBack.height - customView.height) * 0.5 + 2
        
        imageBack.addSubview(customView)
        
    }
    
    //显示当前的 view
    func show(targetButton: UIButton){
        //坐标系转换
        // let rect = __.convertRect(要转换的哪一块区域， 要转到哪一个区域上)
        // 如果 toView为 nil，就代表转换到当前屏幕的 window 上去
        let rect = targetButton.superview!.convertRect(targetButton.frame, toView: nil)
        
        self.imageBack?.centerX = targetButton.centerX
        self.imageBack?.y = CGRectGetMaxY(rect)
        
        //取出 window
        let window = UIApplication.sharedApplication().windows.last
        //添加 button
        window?.addSubview(self)
    }
    
    @objc private func converButtonClick(button: UIButton){
        
        
        if let d = self.delegate {
            // 告诉外界，我消失了，然后执行外界的方法
            d.popViewWillDismiss()
        }
        
        button.removeFromSuperview()
    }
    
}
